<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>rabbitMQ | 有求必应</title><meta name="author" content="Mr.wu"><meta name="copyright" content="Mr.wu"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="一、概念   概念 解释    message 由消息头和消息体组成，消息头由一些可选属性组成   publisher 消息生产者   Exchange 路由。默认直连交换机，名字为空字符，绑定路由键名称与队列名称相同   Binding 将Exchange和queue关联   Queue 队列   virtual host 默认vhost为&#x2F;。本质上是一个mini的rmq服务器，对qu">
<meta property="og:type" content="article">
<meta property="og:title" content="rabbitMQ">
<meta property="og:url" content="https://comortgfytry.github.io/pages/rabbitMQ/rabbitMQ.html">
<meta property="og:site_name" content="有求必应">
<meta property="og:description" content="一、概念   概念 解释    message 由消息头和消息体组成，消息头由一些可选属性组成   publisher 消息生产者   Exchange 路由。默认直连交换机，名字为空字符，绑定路由键名称与队列名称相同   Binding 将Exchange和queue关联   Queue 队列   virtual host 默认vhost为&#x2F;。本质上是一个mini的rmq服务器，对qu">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://comortgfytry.github.io/img/avatar.jpg">
<meta property="article:published_time" content="2023-05-01T03:28:18.000Z">
<meta property="article:modified_time" content="2023-12-10T05:13:12.000Z">
<meta property="article:author" content="Mr.wu">
<meta property="article:tag" content="rabbitMQ">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://comortgfytry.github.io/img/avatar.jpg"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="https://comortgfytry.github.io/pages/rabbitMQ/rabbitMQ.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = {
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":true,"top_n_per_article":1,"unescape":false,"languages":{"hits_empty":"找不到您查询的内容：${query}","hits_stats":"共找到 ${hits} 篇文章"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":300},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  dateSuffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":200,"languages":{"author":"作者: Mr.wu","link":"链接: ","source":"来源: 有求必应","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  },
  autoDarkmode: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'rabbitMQ',
  isPost: true,
  isHome: false,
  isHighlightShrink: undefined,
  isToc: true,
  postUpdate: '2023-12-10 13:13:12'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
    win.getCSS = (url,id = false) => new Promise((resolve, reject) => {
      const link = document.createElement('link')
      link.rel = 'stylesheet'
      link.href = url
      if (id) link.id = id
      link.onerror = reject
      link.onload = link.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        link.onload = link.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(link)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="/css/mycss.css"><style type="text/css"> #universe {  display: block; position: fixed; margin: 0; padding: 0; border: 0; outline: 0; left: 0; top: 0; width: 100%; height: 100%; pointer-events: none; z-index: 1; } </style><meta name="generator" content="Hexo 6.3.0"></head><body><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "" data-lazy-src="/img/avatar.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">63</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">32</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">25</div></a></div><hr class="custom-hr"/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-bookmark"></i><span> 博文</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/categories/"><i class="fa-fw fa fa-archive"></i><span> 分类</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/archives/"><i class="fa-fw fa fa-folder-open"></i><span> 归档</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/comment/"><i class="fa-fw fa fa-paper-plane"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-user"></i><span> 关于我</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://api.aqcoder.cn/random')"><nav id="nav"><span id="blog-info"><a href="/" title="有求必应"><span class="site-name">有求必应</span></a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search" href="javascript:void(0);"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-bookmark"></i><span> 博文</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/categories/"><i class="fa-fw fa fa-archive"></i><span> 分类</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/archives/"><i class="fa-fw fa fa-folder-open"></i><span> 归档</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/comment/"><i class="fa-fw fa fa-paper-plane"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-user"></i><span> 关于我</span></a></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">rabbitMQ</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2023-05-01T03:28:18.000Z" title="发表于 2023-05-01 11:28:18">2023-05-01</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-12-10T05:13:12.000Z" title="更新于 2023-12-10 13:13:12">2023-12-10</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/rabbitMQ/">rabbitMQ</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">2.4k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>11分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="rabbitMQ"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="一、概念"><a href="#一、概念" class="headerlink" title="一、概念"></a>一、概念</h1><table>
<thead>
<tr>
<th>概念</th>
<th>解释</th>
</tr>
</thead>
<tbody><tr>
<td>message</td>
<td>由消息头和消息体组成，消息头由一些可选属性组成</td>
</tr>
<tr>
<td>publisher</td>
<td>消息生产者</td>
</tr>
<tr>
<td>Exchange</td>
<td>路由。默认直连交换机，名字为空字符，绑定路由键名称与队列名称相同</td>
</tr>
<tr>
<td>Binding</td>
<td>将Exchange和queue关联</td>
</tr>
<tr>
<td>Queue</td>
<td>队列</td>
</tr>
<tr>
<td>virtual host</td>
<td>默认vhost为&#x2F;。本质上是一个mini的rmq服务器，对queue、exchange等逻辑分组</td>
</tr>
<tr>
<td>broker</td>
<td>服务器实体</td>
</tr>
<tr>
<td>channel</td>
<td>操控mq的工具</td>
</tr>
</tbody></table>
<h1 id="二、使用"><a href="#二、使用" class="headerlink" title="二、使用"></a>二、使用</h1><h2 id="1、AMQP与Spring-AMQP"><a href="#1、AMQP与Spring-AMQP" class="headerlink" title="1、AMQP与Spring AMQP"></a>1、AMQP与Spring AMQP</h2><ul>
<li>amqp是传递业务消息的协议</li>
<li>spring amqp是基于amqp定义出的一套api规范，提供模板来收发消息。其中spring-amqp是基础抽象，spring-rabbit是底层实现</li>
</ul>
<p>使用准备</p>
<figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">spring:</span></span><br><span class="line">  <span class="attr">rabbitmq:</span></span><br><span class="line">    <span class="attr">host:</span> <span class="string">********</span></span><br><span class="line">    <span class="attr">port:</span> <span class="number">5672</span></span><br><span class="line">    <span class="attr">virtual-host:</span> <span class="string">/</span></span><br><span class="line">    <span class="attr">username:</span> <span class="string">user</span></span><br><span class="line">    <span class="attr">password:</span> <span class="number">1234</span></span><br></pre></td></tr></table></figure>

<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-amqp<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>
<h2 id="2、基础消息队列"><a href="#2、基础消息队列" class="headerlink" title="2、基础消息队列"></a>2、基础消息队列</h2><p>由一个生产者、一个队列、一个消费者组成</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//生产者</span></span><br><span class="line"><span class="meta">@Autowired</span></span><br><span class="line"><span class="keyword">private</span> RabbitTemplate rabbitTemplate;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">simpleQueue</span><span class="params">(String message, String queueName)</span> &#123;</span><br><span class="line">    rabbitTemplate.convertAndSend(queueName,message);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//消费者</span></span><br><span class="line"><span class="meta">@RabbitListener(queues = &quot;simple.queue&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">listenSimpleQueue</span><span class="params">(String message)</span> &#123;</span><br><span class="line">    System.out.println(message);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="3、工作消息队列"><a href="#3、工作消息队列" class="headerlink" title="3、工作消息队列"></a>3、工作消息队列</h2><p>由一个生产者、一个队列、多个消费者组成<br>当队列中有多个消息时，消费者会预抓取（假如有50个消息待处理，那么两个消费者会轮流抓取）。但未来让消费者根据能力抓取，可以设置如下</p>
<figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">//每次只预抓取1个消息，处理后再抓</span></span><br><span class="line"><span class="attr">spring:</span></span><br><span class="line">  <span class="attr">rabbitmq:</span></span><br><span class="line">    <span class="attr">listener:</span></span><br><span class="line">      <span class="attr">simple:</span></span><br><span class="line">        <span class="attr">prefetch:</span> <span class="number">1</span></span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//生产者</span></span><br><span class="line"><span class="meta">@RabbitListener(queues = &quot;work.queue&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">listenWorkQueue1</span><span class="params">(String message)</span> <span class="keyword">throws</span> InterruptedException &#123;</span><br><span class="line">    System.out.println(<span class="string">&quot;1:&quot;</span> + message);</span><br><span class="line">    Thread.sleep(<span class="number">20</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//消费者</span></span><br><span class="line"><span class="meta">@RabbitListener(queues = &quot;work.queue&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">listenWorkQueue1</span><span class="params">(String message)</span> <span class="keyword">throws</span> InterruptedException &#123;</span><br><span class="line">    System.out.println(<span class="string">&quot;1:&quot;</span> + message);</span><br><span class="line">    Thread.sleep(<span class="number">20</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@RabbitListener(queues = &quot;work.queue&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">listenWorkQueue2</span><span class="params">(String message)</span> <span class="keyword">throws</span> InterruptedException &#123;</span><br><span class="line">    System.out.println(<span class="string">&quot;2:&quot;</span> + message);</span><br><span class="line">    Thread.sleep(<span class="number">200</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="4、发布订阅"><a href="#4、发布订阅" class="headerlink" title="4、发布订阅"></a>4、发布订阅</h2><h3 id="（1）广播（Fanout-Exchange）"><a href="#（1）广播（Fanout-Exchange）" class="headerlink" title="（1）广播（Fanout Exchange）"></a>（1）广播（Fanout Exchange）</h3><p>每个消息都会路由到所有队列中<br>一个生产者、一个交换机、多个队列、对应消费者</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//创建交换机、队列，并绑定</span></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">FanoutConfig</span> &#123;</span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> FanoutExchange <span class="title function_">fanoutExchange</span><span class="params">()</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">FanoutExchange</span>(<span class="string">&quot;demo.fanout&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> Queue <span class="title function_">fanoutQueue1</span><span class="params">()</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">Queue</span>(<span class="string">&quot;fanout.queue1&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> Binding <span class="title function_">bindingQueue1</span><span class="params">(Queue fanoutQueue1, FanoutExchange fanoutExchange)</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> BindingBuilder.bind(fanoutQueue1).to(fanoutExchange);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> Queue <span class="title function_">fanoutQueue2</span><span class="params">()</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">Queue</span>(<span class="string">&quot;fanout.queue2&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> Binding <span class="title function_">bindingQueue2</span><span class="params">(Queue fanoutQueue2, FanoutExchange fanoutExchange)</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> BindingBuilder.bind(fanoutQueue2).to(fanoutExchange);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//生产者</span></span><br><span class="line"> <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">fanoutQueue</span><span class="params">(String message, String exchangeName)</span> <span class="keyword">throws</span> InterruptedException &#123;</span><br><span class="line">        rabbitTemplate.convertAndSend(exchangeName,<span class="string">&quot;&quot;</span>, message);</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//消费者</span></span><br><span class="line">    <span class="meta">@RabbitListener(queues = &quot;fanout.queue1&quot;)</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">listenFanoutQueue1</span><span class="params">(String message)</span> <span class="keyword">throws</span> InterruptedException &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;FanoutQueue1:&quot;</span> + message);</span><br><span class="line">        Thread.sleep(<span class="number">20</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@RabbitListener(queues = &quot;fanout.queue2&quot;)</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">listenFanoutQueue2</span><span class="params">(String message)</span> <span class="keyword">throws</span> InterruptedException &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;FanoutQueue2:&quot;</span> + message);</span><br><span class="line">        Thread.sleep(<span class="number">20</span>);</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<h3 id="（2）路由（Direct-Exchange）"><a href="#（2）路由（Direct-Exchange）" class="headerlink" title="（2）路由（Direct Exchange）"></a>（2）路由（Direct Exchange）</h3><p>RoutingKey:列表，用于绑定交换机和队列</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//生产者</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">directQueue</span><span class="params">(String message, String key, String exchangeName)</span> <span class="keyword">throws</span> InterruptedException &#123;</span><br><span class="line">    rabbitTemplate.convertAndSend(exchangeName,key, message);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//消费者</span></span><br><span class="line"><span class="meta">@RabbitListener(bindings = @QueueBinding(</span></span><br><span class="line"><span class="meta">        value = @Queue(&quot;direct.queue1&quot;),</span></span><br><span class="line"><span class="meta">        exchange = @Exchange(value = &quot;demo.direct&quot; ,type = ExchangeTypes.DIRECT),</span></span><br><span class="line"><span class="meta">        key = &#123;&quot;normal&quot;&#125;</span></span><br><span class="line"><span class="meta">))</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">listenDirectQueue1</span><span class="params">(String message)</span> <span class="keyword">throws</span> InterruptedException &#123;</span><br><span class="line">    System.out.println(<span class="string">&quot;DirectQueue1:&quot;</span> + message);</span><br><span class="line">    Thread.sleep(<span class="number">20</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@RabbitListener(bindings = @QueueBinding(</span></span><br><span class="line"><span class="meta">        value = @Queue(&quot;direct.queue2&quot;),</span></span><br><span class="line"><span class="meta">        exchange = @Exchange(value = &quot;demo.direct&quot;,type = ExchangeTypes.DIRECT),</span></span><br><span class="line"><span class="meta">        key = &#123;&quot;special&quot;&#125;</span></span><br><span class="line"><span class="meta">))</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">listenDirectQueue2</span><span class="params">(String message)</span> <span class="keyword">throws</span> InterruptedException &#123;</span><br><span class="line">    System.out.println(<span class="string">&quot;DirectQueue2:&quot;</span> + message);</span><br><span class="line">    Thread.sleep(<span class="number">20</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="（3）主题（Topic-Exchange）"><a href="#（3）主题（Topic-Exchange）" class="headerlink" title="（3）主题（Topic Exchange）"></a>（3）主题（Topic Exchange）</h3><p>BindingKey以.分割，可以使用通配符(#:0个或多个单词；*：一个单词)</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//生产者</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">topicQueue</span><span class="params">(String message, String key, String exchangeName)</span> <span class="keyword">throws</span> InterruptedException &#123;</span><br><span class="line">    rabbitTemplate.convertAndSend(exchangeName,key, message);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//消费者</span></span><br><span class="line"><span class="meta">@RabbitListener(bindings = @QueueBinding(</span></span><br><span class="line"><span class="meta">        value = @Queue(&quot;topic.queue1&quot;),</span></span><br><span class="line"><span class="meta">        exchange = @Exchange(value = &quot;demo.topic&quot;, type = ExchangeTypes.TOPIC),</span></span><br><span class="line"><span class="meta">        key = &#123;&quot;China.#&quot;&#125;</span></span><br><span class="line"><span class="meta">))</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">listenTopicQueue1</span><span class="params">(String message)</span> <span class="keyword">throws</span> InterruptedException &#123;</span><br><span class="line">    System.out.println(<span class="string">&quot;China:&quot;</span> + message);</span><br><span class="line">    Thread.sleep(<span class="number">20</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@RabbitListener(bindings = @QueueBinding(</span></span><br><span class="line"><span class="meta">        value = @Queue(&quot;topic.queue2&quot;),</span></span><br><span class="line"><span class="meta">        exchange = @Exchange(value = &quot;demo.topic&quot;, type = ExchangeTypes.TOPIC),</span></span><br><span class="line"><span class="meta">        key = &#123;&quot;Japan.#&quot;&#125;</span></span><br><span class="line"><span class="meta">))</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">listenTopicQueue2</span><span class="params">(String message)</span> <span class="keyword">throws</span> InterruptedException &#123;</span><br><span class="line">    System.out.println(<span class="string">&quot;Japan:&quot;</span> + message);</span><br><span class="line">    Thread.sleep(<span class="number">20</span>);</span><br><span class="line">&#125;   </span><br></pre></td></tr></table></figure>

<h3 id="（4）headers"><a href="#（4）headers" class="headerlink" title="（4）headers"></a>（4）headers</h3><p>根据发送的消息内容中的headers属性进行路由的。在绑定Queue与Exchange时指定一组键值对</p>
<h1 id="三、消息转换器"><a href="#三、消息转换器" class="headerlink" title="三、消息转换器"></a>三、消息转换器</h1><p>SpringAMQP将消息序列化后发送，并且是由MessageConverter处理，其默认实现为SimpleMessageConverrter,基于jdk的ObjectOutputAStream完成序列化</p>
<p>但可以使用json序列化减小长度</p>
<p>消费者生产者都需要：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>com.fasterxml.jackson.core<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>jackson-databind<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Bean</span></span><br><span class="line"><span class="keyword">public</span> MessageConverter <span class="title function_">messageConverter</span><span class="params">()</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">Jackson2JsonMessageConverter</span>();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h1 id="四、消息丢失"><a href="#四、消息丢失" class="headerlink" title="四、消息丢失"></a>四、消息丢失</h1><p>消息丢失可能有三种原因：  </p>
<ul>
<li>生产到rmq途中</li>
<li>路由不可达</li>
<li>rmq存储时</li>
<li>消费者处理时</li>
</ul>
<p>对应解决方法：  </p>
<ul>
<li>生产者确认机制</li>
<li>return机制和备份机制</li>
<li>持久化</li>
<li>消费者手动确认消息</li>
</ul>
<h2 id="1、生产者确认机制"><a href="#1、生产者确认机制" class="headerlink" title="1、生产者确认机制"></a>1、生产者确认机制</h2><h3 id="（1）事务的方法"><a href="#（1）事务的方法" class="headerlink" title="（1）事务的方法"></a>（1）事务的方法</h3><blockquote>
<p>当消息发送后，生产者阻塞，等待回应后继续</p>
</blockquote>
<h3 id="（2）开启生产者确认的方法"><a href="#（2）开启生产者确认的方法" class="headerlink" title="（2）开启生产者确认的方法"></a>（2）开启生产者确认的方法</h3><figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">spring:</span></span><br><span class="line">    <span class="attr">rabbitmq:</span></span><br><span class="line">        <span class="comment">#开启 confirm 确认机制</span></span><br><span class="line">        <span class="attr">publisher-confirm-type:</span> <span class="string">correlated</span></span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//定义回调</span></span><br><span class="line">rabbitTemplate.setConfirmCallback(<span class="keyword">new</span> <span class="title class_">RabbitTemplate</span>.ConfirmCallback() &#123;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> correlationData convertAndSend相关的配置信息</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> b 表示交换机是否成功收到消息</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> s 表示失败的原因</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">confirm</span><span class="params">(CorrelationData correlationData, <span class="type">boolean</span> b, String s)</span> &#123;</span><br><span class="line">        System.out.println(b);</span><br><span class="line">        <span class="keyword">if</span> (!b) &#123;</span><br><span class="line">            System.out.println(s);</span><br><span class="line">            System.out.println(<span class="string">&quot;异常处理！&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br><span class="line">rabbitTemplate.convertAndSend(exchangeName,<span class="string">&quot;&quot;</span>, message);</span><br><span class="line"></span><br><span class="line"><span class="keyword">try</span> &#123;</span><br><span class="line">    Thread.sleep(<span class="number">2000</span>);</span><br><span class="line">&#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">    e.printStackTrace();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>值得注意的是springamqp自动实现了与rmq建立连接、创建通道的步骤。如果convertAndSend后直接结束进程，那么channel会关闭，由于ConfirmCallback是异步的，所以哪怕消息成功发送，b也会为false，提示：clean channel shutdown; protocol method: #method&lt;channel.close&gt;(reply-code&#x3D;200, reply-text&#x3D;OK, class-id&#x3D;0, method-id&#x3D;0)</p>
</blockquote>
<h2 id="2、return机制和备份机制"><a href="#2、return机制和备份机制" class="headerlink" title="2、return机制和备份机制"></a>2、return机制和备份机制</h2><h3 id="（1）return消息机制"><a href="#（1）return消息机制" class="headerlink" title="（1）return消息机制"></a>（1）return消息机制</h3><p>提供了回调函数returnCallback，当消息从交换机到队列失败时才会调用</p>
<figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">spring:</span></span><br><span class="line">  <span class="attr">rabbitmq:</span></span><br><span class="line">    <span class="attr">template:</span></span><br><span class="line">      <span class="attr">mandatory:</span> <span class="literal">true</span></span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//定义回调</span></span><br><span class="line">rabbitTemplate.setConfirmCallback(<span class="keyword">new</span> <span class="title class_">RabbitTemplate</span>.ConfirmCallback() &#123;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> correlationData convertAndSend相关的配置信息</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> b 表示交换机是否成功收到消息</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> s 表示失败的原因</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">confirm</span><span class="params">(CorrelationData correlationData, <span class="type">boolean</span> b, String s)</span> &#123;</span><br><span class="line">        System.out.println(b);</span><br><span class="line">        <span class="keyword">if</span> (!b) &#123;</span><br><span class="line">            System.out.println(s);</span><br><span class="line">            System.out.println(<span class="string">&quot;异常处理！&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">//return消息（路由不可达）</span></span><br><span class="line">rabbitTemplate.setReturnsCallback(<span class="keyword">new</span> <span class="title class_">RabbitTemplate</span>.ReturnsCallback() &#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">returnedMessage</span><span class="params">(<span class="meta">@NonNull</span> ReturnedMessage returnedMessage)</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;msg: &quot;</span> + <span class="keyword">new</span> <span class="title class_">String</span>(returnedMessage.getMessage().getBody()));</span><br><span class="line">        System.out.println(returnedMessage.getReplyText());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">rabbitTemplate.convertAndSend(exchangeName,<span class="string">&quot;&quot;</span>, message);</span><br><span class="line"></span><br><span class="line"><span class="keyword">try</span> &#123;</span><br><span class="line">    Thread.sleep(<span class="number">2000</span>);</span><br><span class="line">&#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">    e.printStackTrace();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当我们将confirm和return机制都加上，并且由于没有打开消费者，所以交换机上没有绑定队列时，发送消息。由于消息成功到达交换机，所以confirm中b&#x3D;true;但是由于没有队列绑定所以消息路由失败，提示：NO_ROUTE。</p>
<p><img src= "" data-lazy-src="/pages/rabbitMQ/rabbitMQ/image.png" alt="image"></p>
<h3 id="（2）备份交换机"><a href="#（2）备份交换机" class="headerlink" title="（2）备份交换机()"></a>（2）备份交换机()</h3><p>备份交换机alternate-exchange是一个普通的exchange，当你发送消息到对应的exchange时，没有匹<br>配到queue，就会自动转移到备份交换机对应的queue，这样消息就不会丢失。</p>
<blockquote>
<p>注意的是备份交换机和死信交换机的区别是<br>死信交换机处理的是被拒绝、过期、溢出的消息；而备份交换机处理的是未被路由的消息</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//交换机，队列，路由名</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">static</span> String CONFIRM_EXCHANGE=<span class="string">&quot;confirm_exchange&quot;</span>;</span><br><span class="line"><span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">static</span> String CONFIRM_QUEUE=<span class="string">&quot;confirm_queue&quot;</span>;</span><br><span class="line"><span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">static</span> String CONFIRM_ROUTING_KEY=<span class="string">&quot;confirm&quot;</span>;</span><br><span class="line"> </span><br><span class="line"><span class="comment">//备份队列，交换机,报警队列</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">static</span>  String BACKUP_EXCHANGE=<span class="string">&quot;backup_exchange&quot;</span>;</span><br><span class="line"><span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">static</span>  String BACKUP_QUEUE=<span class="string">&quot;backup_queue&quot;</span>;</span><br><span class="line"><span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">static</span>  String WARNING_QUEUE=<span class="string">&quot;warning_queue&quot;</span>;</span><br><span class="line"> </span><br><span class="line"><span class="comment">//声明交普通换机，队列</span></span><br><span class="line"><span class="meta">@Bean</span></span><br><span class="line"><span class="keyword">public</span> DirectExchange <span class="title function_">confirmExchange</span><span class="params">()</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> ExchangeBuilder.directExchange(CONFIRM_EXCHANGE).durable(<span class="literal">true</span>)</span><br><span class="line">            <span class="comment">//普通交换机声明其备份交换机</span></span><br><span class="line">            .withArgument(<span class="string">&quot;alternate-exchange&quot;</span>,BACKUP_EXCHANGE).build();</span><br><span class="line">&#125;</span><br><span class="line"><span class="meta">@Bean</span></span><br><span class="line"><span class="keyword">public</span> Queue <span class="title function_">confirmQueue</span><span class="params">()</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> QueueBuilder.durable(CONFIRM_QUEUE).build();</span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line"><span class="comment">//绑定交换机和队列</span></span><br><span class="line"><span class="meta">@Bean</span></span><br><span class="line"><span class="keyword">public</span> Binding <span class="title function_">queueBindExchange</span><span class="params">(<span class="meta">@Qualifier(&quot;confirmExchange&quot;)</span> DirectExchange exchange,</span></span><br><span class="line"><span class="params">                                 <span class="meta">@Qualifier(&quot;confirmQueue&quot;)</span> Queue queue)</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> BindingBuilder.bind(queue).to(exchange).with(CONFIRM_ROUTING_KEY);</span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line"><span class="comment">//备份交换机，备份队列，报警队列声明即绑定</span></span><br><span class="line"><span class="meta">@Bean</span></span><br><span class="line"><span class="keyword">public</span> FanoutExchange <span class="title function_">backupExchange</span><span class="params">()</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> ExchangeBuilder.fanoutExchange(BACKUP_EXCHANGE).build();</span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line"><span class="meta">@Bean</span></span><br><span class="line"><span class="keyword">public</span> Queue <span class="title function_">backupQueue</span><span class="params">()</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> QueueBuilder.durable(BACKUP_QUEUE).build();</span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line"><span class="meta">@Bean</span></span><br><span class="line"><span class="keyword">public</span> Queue <span class="title function_">warningQueue</span><span class="params">()</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> QueueBuilder.durable(WARNING_QUEUE).build();</span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line"><span class="meta">@Bean</span></span><br><span class="line"><span class="keyword">public</span> Binding <span class="title function_">backExchangeBindbackQueue</span><span class="params">(<span class="meta">@Qualifier(&quot;backupExchange&quot;)</span> FanoutExchange fanoutExchange,</span></span><br><span class="line"><span class="params">                                         <span class="meta">@Qualifier(&quot;backupQueue&quot;)</span> Queue queue)</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> BindingBuilder.bind(queue).to(fanoutExchange);</span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line"><span class="meta">@Bean</span></span><br><span class="line"><span class="keyword">public</span> Binding <span class="title function_">warningQueueBindBackQueue</span><span class="params">(<span class="meta">@Qualifier(&quot;backupExchange&quot;)</span> FanoutExchange exchange,</span></span><br><span class="line"><span class="params">                                         <span class="meta">@Qualifier(&quot;warningQueue&quot;)</span> Queue queue)</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> BindingBuilder.bind(queue).to(exchange);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>当然还有注解的方式来绑定</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RabbitListener(bindings = @QueueBinding(</span></span><br><span class="line"><span class="meta">        value = @Queue(&quot;direct.queue2&quot;),</span></span><br><span class="line"><span class="meta">        exchange = @Exchange(value = &quot;demo.direct&quot;,type = ExchangeTypes.DIRECT),</span></span><br><span class="line"><span class="meta">        arguments = @Argument(name = &quot;alternate-exchange&quot;, value = &quot;direct.alternate&quot;),</span></span><br><span class="line"><span class="meta">        key = &#123;&quot;special&quot;&#125;</span></span><br><span class="line"><span class="meta">))</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">listenDirectQueue2</span><span class="params">(String message)</span> <span class="keyword">throws</span> InterruptedException &#123;</span><br><span class="line">    System.out.println(<span class="string">&quot;DirectQueue2:&quot;</span> + message);</span><br><span class="line">    Thread.sleep(<span class="number">20</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="3、持久化"><a href="#3、持久化" class="headerlink" title="3、持久化"></a>3、持久化</h2><p>条件：</p>
<ul>
<li>queue持久化</li>
<li>Exchange持久化<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RabbitListener(bindings = @QueueBinding(</span></span><br><span class="line"><span class="meta">        value = @Queue(value = &quot;direct.queue1&quot;, durable = &quot;true&quot;),</span></span><br><span class="line"><span class="meta">        exchange = @Exchange(value = &quot;demo.direct&quot; ,type = ExchangeTypes.DIRECT, durable = &quot;true&quot;),</span></span><br><span class="line"><span class="meta">        key = &#123;&quot;normal&quot;&#125;</span></span><br><span class="line"><span class="meta">))</span></span><br></pre></td></tr></table></figure></li>
<li>消息设置持久化<blockquote>
<p>使用convertAndSend发送消息，默认就是持久化的</p>
</blockquote>
</li>
</ul>
<h2 id="4、消费者手动确认消息"><a href="#4、消费者手动确认消息" class="headerlink" title="4、消费者手动确认消息"></a>4、消费者手动确认消息</h2><blockquote>
<p>默认情况下，消费者自动确认消息 ,MQ收到后就会移除这一消息<br>但是更稳妥的做法是采用手动确认，等消费者完成逻辑处理后再手动ack。</p>
</blockquote>
<figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">spring.rabbitmq.listener.simple.acknowledge-mode=manual</span></span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RabbitListener(queues = &quot;simple.queue&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">listenSimpleQueue</span><span class="params">(Message message, Channel channel)</span> <span class="keyword">throws</span> IOException &#123;</span><br><span class="line">    <span class="type">long</span> <span class="variable">deliveryTag</span> <span class="operator">=</span> message.getMessageProperties().getDeliveryTag();</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;处理消息&quot;</span>);</span><br><span class="line">        System.out.println(<span class="keyword">new</span> <span class="title class_">String</span>(message.getBody()));</span><br><span class="line">        <span class="comment">//手动ack(true:确认所有消息，false:只确认当前消息)</span></span><br><span class="line">        channel.basicAck(deliveryTag, <span class="literal">false</span>);</span><br><span class="line">        Thread.sleep(<span class="number">5000</span>);</span><br><span class="line">    &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">        <span class="comment">//b:ack返回false；b1:是否重新返回队列</span></span><br><span class="line">        channel.basicNack(deliveryTag, <span class="literal">false</span>, <span class="literal">true</span>);</span><br><span class="line">        e.printStackTrace();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h1 id="五、死信队列"><a href="#五、死信队列" class="headerlink" title="五、死信队列"></a>五、死信队列</h1><p>消费失败消息存放的队列（被拒绝、过期、溢出的消息）</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RabbitListener(bindings = @QueueBinding(</span></span><br><span class="line"><span class="meta">        value = @Queue(&quot;direct.queue2&quot;),</span></span><br><span class="line"><span class="meta">        exchange = @Exchange(value = &quot;demo.direct&quot;,type = ExchangeTypes.DIRECT),</span></span><br><span class="line"><span class="meta">        arguments = @Argument(name = &quot;x-dead-letter-exchange&quot;, value = &quot;direct.dead&quot;),</span></span><br><span class="line"><span class="meta">        key = &#123;&quot;special&quot;&#125;</span></span><br><span class="line"><span class="meta">))</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">listenDirectQueue2</span><span class="params">(String message)</span> <span class="keyword">throws</span> InterruptedException &#123;</span><br><span class="line">    System.out.println(<span class="string">&quot;DirectQueue2:&quot;</span> + message);</span><br><span class="line">    Thread.sleep(<span class="number">20</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h1 id="六、如何保障消息的顺序性"><a href="#六、如何保障消息的顺序性" class="headerlink" title="六、如何保障消息的顺序性"></a>六、如何保障消息的顺序性</h1><ul>
<li>单线程</li>
<li>编号</li>
</ul>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://comortgfytry.github.io">Mr.wu</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://comortgfytry.github.io/pages/rabbitMQ/rabbitMQ.html">https://comortgfytry.github.io/pages/rabbitMQ/rabbitMQ.html</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://comortgfytry.github.io" target="_blank">有求必应</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/rabbitMQ/">rabbitMQ</a></div><div class="post_share"><div class="social-share" data-image="/img/avatar.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/pages/mybatis/mybatis.html" title="mybatis"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">mybatis</div></div></a></div><div class="next-post pull-right"><a href="/pages/Mysql/count%E7%9A%84%E8%AE%A1%E6%95%B0.html" title="count的计数"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">count的计数</div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src= "" data-lazy-src="/img/avatar.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">Mr.wu</div><div class="author-info__description">分享知识</div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">63</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">32</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">25</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/xxxxxx"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/xxxxxx" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="https://blog.csdn.net/blue_gym" target="_blank" title="CSDN"><i class="fa fa-book-open"></i></a><a class="social-icon" href="mailto:shouwangyinying@163.com" target="_blank" title="Email"><i class="fas fa-envelope-open-text"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">Nice to meet you. please get website connection by Ctrl + F5</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%B8%80%E3%80%81%E6%A6%82%E5%BF%B5"><span class="toc-number">1.</span> <span class="toc-text">一、概念</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%BA%8C%E3%80%81%E4%BD%BF%E7%94%A8"><span class="toc-number">2.</span> <span class="toc-text">二、使用</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1%E3%80%81AMQP%E4%B8%8ESpring-AMQP"><span class="toc-number">2.1.</span> <span class="toc-text">1、AMQP与Spring AMQP</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2%E3%80%81%E5%9F%BA%E7%A1%80%E6%B6%88%E6%81%AF%E9%98%9F%E5%88%97"><span class="toc-number">2.2.</span> <span class="toc-text">2、基础消息队列</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3%E3%80%81%E5%B7%A5%E4%BD%9C%E6%B6%88%E6%81%AF%E9%98%9F%E5%88%97"><span class="toc-number">2.3.</span> <span class="toc-text">3、工作消息队列</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4%E3%80%81%E5%8F%91%E5%B8%83%E8%AE%A2%E9%98%85"><span class="toc-number">2.4.</span> <span class="toc-text">4、发布订阅</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%EF%BC%881%EF%BC%89%E5%B9%BF%E6%92%AD%EF%BC%88Fanout-Exchange%EF%BC%89"><span class="toc-number">2.4.1.</span> <span class="toc-text">（1）广播（Fanout Exchange）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%EF%BC%882%EF%BC%89%E8%B7%AF%E7%94%B1%EF%BC%88Direct-Exchange%EF%BC%89"><span class="toc-number">2.4.2.</span> <span class="toc-text">（2）路由（Direct Exchange）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%EF%BC%883%EF%BC%89%E4%B8%BB%E9%A2%98%EF%BC%88Topic-Exchange%EF%BC%89"><span class="toc-number">2.4.3.</span> <span class="toc-text">（3）主题（Topic Exchange）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%EF%BC%884%EF%BC%89headers"><span class="toc-number">2.4.4.</span> <span class="toc-text">（4）headers</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%B8%89%E3%80%81%E6%B6%88%E6%81%AF%E8%BD%AC%E6%8D%A2%E5%99%A8"><span class="toc-number">3.</span> <span class="toc-text">三、消息转换器</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%9B%9B%E3%80%81%E6%B6%88%E6%81%AF%E4%B8%A2%E5%A4%B1"><span class="toc-number">4.</span> <span class="toc-text">四、消息丢失</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1%E3%80%81%E7%94%9F%E4%BA%A7%E8%80%85%E7%A1%AE%E8%AE%A4%E6%9C%BA%E5%88%B6"><span class="toc-number">4.1.</span> <span class="toc-text">1、生产者确认机制</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%EF%BC%881%EF%BC%89%E4%BA%8B%E5%8A%A1%E7%9A%84%E6%96%B9%E6%B3%95"><span class="toc-number">4.1.1.</span> <span class="toc-text">（1）事务的方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%EF%BC%882%EF%BC%89%E5%BC%80%E5%90%AF%E7%94%9F%E4%BA%A7%E8%80%85%E7%A1%AE%E8%AE%A4%E7%9A%84%E6%96%B9%E6%B3%95"><span class="toc-number">4.1.2.</span> <span class="toc-text">（2）开启生产者确认的方法</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2%E3%80%81return%E6%9C%BA%E5%88%B6%E5%92%8C%E5%A4%87%E4%BB%BD%E6%9C%BA%E5%88%B6"><span class="toc-number">4.2.</span> <span class="toc-text">2、return机制和备份机制</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%EF%BC%881%EF%BC%89return%E6%B6%88%E6%81%AF%E6%9C%BA%E5%88%B6"><span class="toc-number">4.2.1.</span> <span class="toc-text">（1）return消息机制</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%EF%BC%882%EF%BC%89%E5%A4%87%E4%BB%BD%E4%BA%A4%E6%8D%A2%E6%9C%BA"><span class="toc-number">4.2.2.</span> <span class="toc-text">（2）备份交换机()</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3%E3%80%81%E6%8C%81%E4%B9%85%E5%8C%96"><span class="toc-number">4.3.</span> <span class="toc-text">3、持久化</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4%E3%80%81%E6%B6%88%E8%B4%B9%E8%80%85%E6%89%8B%E5%8A%A8%E7%A1%AE%E8%AE%A4%E6%B6%88%E6%81%AF"><span class="toc-number">4.4.</span> <span class="toc-text">4、消费者手动确认消息</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%BA%94%E3%80%81%E6%AD%BB%E4%BF%A1%E9%98%9F%E5%88%97"><span class="toc-number">5.</span> <span class="toc-text">五、死信队列</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%85%AD%E3%80%81%E5%A6%82%E4%BD%95%E4%BF%9D%E9%9A%9C%E6%B6%88%E6%81%AF%E7%9A%84%E9%A1%BA%E5%BA%8F%E6%80%A7"><span class="toc-number">6.</span> <span class="toc-text">六、如何保障消息的顺序性</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/pages/%E7%AE%97%E6%B3%95/%E6%99%AE%E9%80%9A%E6%95%B0%E7%BB%84/%E7%BC%BA%E5%A4%B1%E7%9A%84%E7%AC%AC%E4%B8%80%E4%B8%AA%E6%AD%A3%E6%95%B0.html" title="缺失的第一个正数">缺失的第一个正数</a><time datetime="2024-01-06T13:48:58.072Z" title="发表于 2024-01-06 21:48:58">2024-01-06</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/pages/%E7%AE%97%E6%B3%95/%E7%9F%A9%E9%98%B5/%E7%9F%A9%E9%98%B5%E7%BD%AE%E9%9B%B6.html" title="矩阵置零">矩阵置零</a><time datetime="2024-01-06T13:48:58.070Z" title="发表于 2024-01-06 21:48:58">2024-01-06</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/pages/RPC%E6%A1%86%E6%9E%B6/%E6%9C%8D%E5%8A%A1%E8%BF%9C%E7%A8%8B%E8%B0%83%E7%94%A8(RestTemplate%E3%80%81Feign%E3%80%81Dubbo).html" title="服务远程调用(RestTemplate、Feign、Dubbo)">服务远程调用(RestTemplate、Feign、Dubbo)</a><time datetime="2023-12-30T02:24:00.000Z" title="发表于 2023-12-30 10:24:00">2023-12-30</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/pages/%E8%BD%AF%E4%BB%B6%E6%9E%B6%E6%9E%84/%E8%BD%AF%E4%BB%B6%E6%9E%B6%E6%9E%84%E5%A4%8D%E4%B9%A0.html" title="软件架构复习">软件架构复习</a><time datetime="2023-12-23T15:50:20.000Z" title="发表于 2023-12-23 23:50:20">2023-12-23</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/pages/%E7%AE%97%E6%B3%95/%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE/%E6%90%9C%E7%B4%A2%E4%BA%8C%E7%BB%B4%E7%9F%A9%E9%98%B5.html" title="搜索二维矩阵 - 算法 - 二分查找">搜索二维矩阵 - 算法 - 二分查找</a><time datetime="2023-12-04T04:50:20.000Z" title="发表于 2023-12-04 12:50:20">2023-12-04</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('https://api.aqcoder.cn/random')"><div id="footer-wrap"><div class="copyright">&copy;2023 - 2024 By Mr.wu</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox/fancybox.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><div class="js-pjax"></div><canvas id="universe"></canvas>'<script src="/js/universe.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = true;
POWERMODE.mobile = false;
document.body.addEventListener('input', POWERMODE);
</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div class="no-result" id="local-search-results"></div><div id="local-search-stats-wrap"></div></div></div><div id="search-mask"></div><script src="/js/search/local-search.js"></script></div></div><script async>window.onload=function(){var a=document.createElement('script'),b=document.getElementsByTagName('script')[0];a.type='text/javascript',a.async=!0,a.src='/sw-register.js?v='+Date.now(),b.parentNode.insertBefore(a,b)};</script></body></html>